import { Component } from '@angular/core';
import { NzModalService, NzModalRef, NzNotificationService } from 'ng-zorro-antd';
import { SiteService } from '@srvs/site.service';
import { ApiService } from '@srvs/api.service';

import { EditUserComponent } from './edit-user/edit-user.component';
import { EditRoleComponent } from '../role-management/edit-role/edit-role.component';

@Component({
  selector: 'user-management',
  templateUrl: './user-management.component.html',
  styles: [`
    :host ::ng-deep .roles .ant-card-head {
      margin-bottom: 0;
    }
    :host ::ng-deep .roles .ant-card-body {
      padding: 0;
    }
    :host ::ng-deep .roles .add-roles {
      transition: color 0.3s;
    }
    :host ::ng-deep .roles .add-roles:hover {
      color: #1890ff;
    }
  `]
})
export class UserManagementComponent {

  public config: any = {
    userCount: 0,
    userHiddenCount: 0,
    badgeStyle: { backgroundColor: '#d7d7d7', color: '#ffffff', boxShadow: 'none' },
    userLoading: false,
    allChecked: false,
    indeterminate: false,
    userStatusOption: [
      { text: '有效', value: true },
      { text: '无效', value: false }
    ],
    userStatus: [],
    expiryDateSort: null,
    lastModifiedTimeSort: null
  };
  public data: any = {
    roles: [],
    users: [],
    displayUsers: []
  };
  public params: any = {
    siteId: null,
    roleId: null,
    keywords: null
  };
  private debounce: any;

  constructor(
    public siteSrv: SiteService,
    private modalSrv: NzModalService,
    private apiSrv: ApiService,
    private msgSrv: NzNotificationService
  ) {
    const site: any = this.siteSrv.site || {};
    this.params.siteId = site.id;
    this.load();
  }

  /**
   * 加载初始化数据
   */
  public load(): void {
    const apiRoles: string = `/api/sites/${this.params.siteId}/roles`;
    this.apiSrv.get(apiRoles).subscribe(
      roles => {
        this.data.roles = roles;
        this.loadUsers();
      },
      error => this.msgSrv.error('站点角色列表加载失败！', error.message)
    );
  }

  /**
   * 加载用户列表
   */
  public loadUsers(): void {
    const apiUsers: string = this.params.keywords
      ? `/api/_search/users?query="${this.params.keywords}" AND sites.id:${this.params.siteId}`
      : `/api/sites/${this.params.siteId}/users`;
    this.config.userLoading = true;
    this.apiSrv.get(apiUsers).subscribe(
      (users: any[]) => {
        this.data.users = users;
        // this.data.users.forEach(item => item.checked = false);
        this.refreshUserCountByRole();
        this.changeRole(this.params.roleId);
        this.config.userLoading = false;
      },
      error => this.msgSrv.error('站点用户列表获取失败！', error.message)
    );
  }

  /**
   * 改变站点
   * @param value 站点值（公司id，站点id）
   */
  public changeSite(value: [number, number]): void {
    this.params.siteId = value[1];
    this.params.roleId = null;
    this.load();
  }

  /**
   * 改变角色
   * @param roleId 角色id
   */
  public changeRole(roleId: number): void {
    this.params.roleId = roleId;
    this.data.displayUsers = roleId
      ? this.data.users.filter(userItem => !!userItem.roles.find(roleItem => roleItem.id === roleId))
      : this.data.users;
    this.filterStatus(this.config.userStatus);
    if (this.config.expiryDateSort) {
      this.sortExpiryDate(this.config.expiryDateSort);
    }
    if (this.config.lastModifiedTimeSort) {
      this.sortLastModifiedTime(this.config.lastModifiedTimeSort);
    }
  }

  /**
   * 更新角色的用户数量
   */
  private refreshUserCountByRole(): void {
    let rolesObject: any = {};
    this.config.userCount = this.data.users.length;
    this.data.users.forEach(userItem => {
      userItem.roles.forEach(roleItem => {
        rolesObject[roleItem.id] = rolesObject[roleItem.id] || 0;
        rolesObject[roleItem.id]++;
      });
    });
    this.data.roles.forEach(item => item.userCount = rolesObject[item.id] || 0);
  }

  /**
   * 更新隐藏的用户数量
   */
  private refreshUserHiddenCount(): void {
    const userTotal: number = this.params.roleId
      ? this.data.roles.find(item => item.id === this.params.roleId).userCount
      : this.data.users.length;
    this.config.userHiddenCount = userTotal - this.data.displayUsers.length;
  }

  /**
   * 更新用户列表选中状态
   */
  // public refreshStatus(): void {
  //   const allChecked = this.data.displayUsers.every(value => value.checked === true);
  //   const allUnChecked = this.data.displayUsers.every(value => !value.checked);
  //   this.config.allChecked = allChecked;
  //   this.config.indeterminate = !allChecked && !allUnChecked;
  // }

  /**
   * 选中用户列表当前页的所有用户
   * @param value 选中状态
   */
  // public checkAll(value: boolean): void {
  //   this.data.displayUsers.forEach(data => data.checked = value);
  //   this.refreshStatus();
  // }

  /**
   * 按用户状态筛选用户
   */
  public filterStatus(status: any[]): void {
    let displayUsers: any[];
    displayUsers = this.params.roleId
      ? this.data.users.filter(userItem => !!userItem.roles.find(roleItem => roleItem.id === this.params.roleId))
      : this.data.users;
    displayUsers = status.length
      ? displayUsers.filter(userItem => status.includes(userItem.isValid))
      : displayUsers;
    this.config.userStatus = status;
    this.data.displayUsers = displayUsers;
    this.refreshUserHiddenCount();
  }

  /**
   * 按失效日期排序用户列表
   * @param sort 排序
   */
  public sortExpiryDate(sort: string): void {
    const displayUsers: any[] = [...this.data.displayUsers];
    displayUsers.sort((a: any, b: any) => {
      switch (sort) {
        case 'ascend':
          return new Date(a.expiredTime).valueOf() - new Date(b.expiredTime).valueOf();
        case 'descend':
          return new Date(b.expiredTime).valueOf() - new Date(a.expiredTime).valueOf();
        default:
          return a.id - b.id;
      }
    });
    this.data.displayUsers = displayUsers;
    this.config.lastModifiedTimeSort = null;
  }

  /**
   * 按最后更新时间排序用户列表
   * @param sort 排序
   */
  public sortLastModifiedTime(sort: string): void {
    const displayUsers: any[] = [...this.data.displayUsers];
    displayUsers.sort((a: any, b: any) => {
      switch (sort) {
        case 'ascend':
          return new Date(a.lastModifiedTime).valueOf() - new Date(b.lastModifiedTime).valueOf();
        case 'descend':
          return new Date(b.lastModifiedTime).valueOf() - new Date(a.lastModifiedTime).valueOf();
        default:
          return a.id - b.id;
      }
    });
    this.data.displayUsers = displayUsers;
    this.config.expiryDateSort = null;
  }

  /**
   * 创建用户
   */
  public createUser(): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '创建用户',
      nzContent: EditUserComponent,
      nzComponentParams: { roleOptions: this.data.roles },
      nzWidth: 992,
      nzMaskClosable: false,
      nzOnOk: (component: EditUserComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            // data.checked = false;
            this.data.users = [...this.data.users, data];
            this.refreshUserCountByRole();
            this.changeRole(this.params.roleId);
            this.msgSrv.success('创建用户成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('创建用户失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 修改用户
   * @param user 用户数据
   */
  public editUser(user: any): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '修改用户',
      nzContent: EditUserComponent,
      nzComponentParams: { data: user, roleOptions: this.data.roles },
      nzWidth: 992,
      nzMaskClosable: false,
      nzOnOk: (component: EditUserComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            const index: number = this.data.users.findIndex(item => item.id === user.id),
              users: any[] = [...this.data.users];
            // data.checked = users[index].checked;
            users[index] = data;
            this.data.users = users;
            this.changeRole(this.params.roleId);
            this.msgSrv.success('修改用户成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('修改用户失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 删除用户
   * @param user 用户数据
   */
  public deleteUser(user: any): void {
    const deleteUser: string = `/api/users/${user.id}`;
    this.apiSrv.delete(deleteUser).subscribe(
      () => {
        this.data.users = this.data.users.filter(item => item !== user);
        this.data.displayUsers = this.data.displayUsers.filter(item => item !== user);
        this.refreshUserCountByRole();
        this.changeRole(this.params.roleId);
        this.msgSrv.success('删除用户成功！', null);
      },
      error => this.msgSrv.error('删除用户失败！', error.message)
    );
  }

  /**
   * 创建角色
   */
  public createRole(): void {
    const ref: NzModalRef = this.modalSrv.create({
      nzTitle: '创建角色',
      nzContent: EditRoleComponent,
      nzWidth: 576,
      nzMaskClosable: false,
      nzOnOk: (component: EditRoleComponent) => {
        ref.getInstance().nzOkLoading = true;
        component.submit().subscribe(
          data => {
            this.data.roles = [...this.data.roles, data];
            this.refreshUserCountByRole();
            this.msgSrv.success('创建角色成功！', null);
            ref.destroy();
          },
          error => {
            this.msgSrv.error('创建用户失败！', error.message);
            ref.getInstance().nzOkLoading = false;
          },
          () => ref.getInstance().nzOkLoading = false
        );
        return false;
      }
    });
  }

  /**
   * 防抖动加载用户数据
   */
  public debounceLoadUsers(): void {
    clearTimeout(this.debounce);
    this.debounce = setTimeout(() => this.loadUsers(), 500);
  }

}
